<template>
	<view class="page">
		<view class="title">
			<text>{{LineName}}</text>
			<text style="margin-top: 20rpx;">发车时间：{{timeFormat(SetOutTime)}}</text>
		</view>
		<scroll-view scroll-y style="height: 62vh;">
			<view class="people" v-for="(p,index) in airBookInfos" :key="index">
				<view class="name">
					{{p.name}}：
				</view>
				<view>
					<view class="photo" v-if="!p.idCardPath" @click="takePhoto('1',p)">
						<u-icon name="camera" size="60" color="#909399"></u-icon>
					</view>
					<view style="text-align: center;" v-else>
						<image @click="showOrTake('1',p)" :src="p.idCardPath" class="img">
						</image>
						<text>身份证</text>
					</view>
					<view v-if="!p.idCardPath" style="margin-top: 20rpx;text-align: center;color: #909399;">上传身份证</view>
				</view>

				<view>
					<view class="photo" v-if="!p.boardingPassPath" @click="takePhoto('2',p)">
						<u-icon name="camera" size="60" color="#909399"></u-icon>
					</view>
					<view style="text-align: center;" v-else>
						<image @click="showOrTake('2',p)" :src="p.boardingPassPath" class="img">
						</image>
						<text>登机牌</text>
					</view>
					<view v-if="!p.boardingPassPath" style="margin-top: 20rpx;text-align: center;color: #909399;">上传登机牌
					</view>
				</view>
				<view>
					<view class="photo" v-if="!p.ticketPath" @click="takePhoto('3',p)">
						<u-icon name="camera" size="60" color="#909399"></u-icon>
					</view>
					<view style="text-align: center;" v-else>
						<image @click="showOrTake('3',p)" :src="p.ticketPath" class="img">
						</image>
						<text>车票</text>
					</view>
					<view v-if="!p.ticketPath" style="margin-top: 20rpx;text-align: center;color: #909399;">上传车票
					</view>
				</view>
				<view :style="{color:stateColor(p.state)}" class="state">
					{{p.stateDesc}}
				</view>
			</view>
		</scroll-view>
		<view style="display: flex;justify-content: center;width: 100%;margin-top: 80rpx;">
			<view style="width: 80%;">
				<u-button type="primary" @click="GetLogs()" shape="circle" plain>查看订单流程记录</u-button>
			</view>
		</view>
		<!-- 拍摄提示信息 -->
		<u-modal v-model="showMsg" width="80%">
			<view class="slot-content" style="padding: 10rpx;font-size: 28rpx;color: #b6b6b6;width: 100%;">
				<rich-text :nodes="content"></rich-text>
			</view>
		</u-modal>
		<u-popup v-model="showFlow" mode='bottom' border-radius="10">
			<uni-section title="订单流程" type="line" padding>
				<scroll-view scroll-y style="height: 60vh;">
					<view class="item" v-for="(item,index) in logs" :key="index">
						<view>
							<view class="yuan"></view>
							<view class="line"></view>
						</view>
						<view class="item_txt">
							<view class="txt">
								<view style="display: flex;flex-direction: column;">
									<view class="time">
										{{formata(item.OccurTime)}}
									</view>
									<!-- <view tyle="height: 40rpx;color: #ee9b22;">上传身份证</view> -->
									<view class="messsage">
										{{item.Message}}
									</view>
								</view>
							</view>
						</view>

					</view>
				</scroll-view>

			</uni-section>
		</u-popup>
		<canvas canvas-id="watermarkCanvas" id="watermarkCanvas" class="mark-canvas"
			:style="{width: canvasWidth+'px',height: canvasHeight+'px'}"></canvas>
		<u-toast ref="uToast" />
	</view>
</template>

<script>
	var _self;
	import UniSection from '@/uni_modules/uni-section/uni-section.vue'
	export default {
		components: {
			UniSection
		}, 
		data() {
			return {
				action: 'http://www.example.com/upload',
				fileList: [],
				canvas: null,
				canvasWidth: "",
				canvasHeight: "",
				type: '1',
				ticketID: '',
				airBookInfos: [],
				BookLogAID:  "",
				LineName:  "",
				SetOutTime: null,
				// ticketInfo: {
					
				// },
				showMsg: true,
				content: `<p>平台将严格遵守个人隐私政策，照片信息仅用于补贴审核。</p>
						<p>拍摄要求及补贴说明:</p>
						<p>1.照片需四角对齐，信息完整。请避免出现模糊、反光、过期等情况。</p>
						<p>2.上传的照片信息需要与乘机人信息一致。</p>
						<p>3.身份证照片与登记牌照片都需要上传才能进入审核状态。</p>
						<p>4.照片上传完整后审核将在1-7个工作日内完成，审核通过将原路退款，退款金额以具体活动公告为准。</p>
						<p>5.每个订单的有效上传时间为24小时，请务必及时上传。</p>
						<p>6.每个订单的最多可审核2次，请认真核对并按平台要求上传，避免订单失效。</p>`,
				showFlow: false,
				logs: []

			};
		},
		mounted() {
			// 在组件挂载后获取 canvas 节点
			this.getCanvasNode();
			uni.hideLoading()

		},
		onLoad(option) {
			_self = this;
			uni.showLoading({
				title: '加载中...'
			})
			console.log('111',option);
			_self.BookLogAID = option.AID;
			_self.LineName = option.LineName;
			_self.SetOutTime = option.SetOutTime;
			this.GetAirBookInfosByID(_self.BookLogAID);
		},
		methods: {
			GetAirBookInfosByID: function(bookID) {
				uni.showLoading({
					title: '获取订单流程中...'
				})
					//if (_self.indexnumber > 100) {
					uni.request({
						url: _self.$h.expressInterface.expressInterface.GetAirBookInfosByID.url, 
						method: _self.$h.expressInterface.expressInterface.GetAirBookInfosByID.method,
						header: _self.$h.expressInterface.expressInterface.GetAirBookInfosByID.header, 
						data: {
							BookLogAID: bookID
						},
						success: function(res) {
							console.log('111',res);
							if (res.data.IsSuccess) {
								_self.airBookInfos = res.data.Data;
								console.log('001',_self.airBookInfos[0]);
								uni.hideLoading()
								
							} else {
								
							}
						},
						fail: function(res) {
							console.log('失败返回', res);
							_self.showToast(res.data.Message, 'error');
						}
					})
			},
			//获取日志
			GetLogs: function() {
				uni.showLoading({
					title: '获取订单流程中...'
				})
					//if (_self.indexnumber > 100) {
					uni.request({
						url: _self.$h.expressInterface.expressInterface.GetLogs.url,
						method: _self.$h.expressInterface.expressInterface.GetLogs.method,
						header: _self.$h.expressInterface.expressInterface.GetLogs.header,
						data: {
							BookLogAID: _self.BookLogAID
						},
						success: function(res) {
							console.log(res);
							if (res.data.IsSuccess) {
								_self.logs = res.data.Data;
								_self.showFlow = true;
								uni.hideLoading()
								
							} else {
								
							}
						},
						fail: function(res) {
							console.log('失败返回', res);
							_self.showToast(res.data.Message, 'error');
						}
					})
			},
			//预览图片
			previewImage(watermarkedImagePath) {
				let that = this
				if (watermarkedImagePath) {
					uni.previewImage({
						current: watermarkedImagePath, // 当前显示图片的http链接
						urls: [watermarkedImagePath] // 需要预览的图片http链接列表
					});
				} else {
					uni.showToast({
						title: '暂无预览图片',
						icon: 'none'
					});
				}
			},
			//获取canvas节点
			getCanvasNode() {
				// 使用 uni.createSelectorQuery 获取 canvas 节点
				const query = uni.createSelectorQuery().in(this);
				query
					.select('#watermarkCanvas')
					.fields({
						node: true,
						size: true
					})
					.exec((res) => {
						if (res[0]) {
							const canvas = res[0];
							// 将 canvas 节点保存到组件实例中
							this.canvas = canvas;
						}
					});
			},
			//预览或者重新上传
			showOrTake(type, people) {
				let that = this
				let list = []
				let list_one = ['预览图片']
				let list_two = ['预览图片', '重新上传']
				if (people.state !== 3 || people.state !== 5 || people.state !== 7) {
					list = list_two
				} else {
					list = list_one
				}
				uni.showActionSheet({
					itemList: list, // 示例号码列表
					success: function(res) {
						if (res.tapIndex == 0) {
							if (type == 1) {
								that.previewImage(people.idCardPath)
							} else if (type == 2) {
								that.previewImage(people.boardingPassPath)
							} else {
								that.previewImage(people.ticketPath)
							}
						} else {
							that.takePhoto(type, people)
						}
					},
					fail: function(res) {
						console.log(res.errMsg);
					}
				});
			},
			// 拍照获取图片
			takePhoto(type, people) {
				const that = this;
				uni.chooseImage({
					count: 1,
					sourceType: ['camera'],
					success(res) {
						uni.showLoading({
							title: '图片加载中...'
						});
						setTimeout(() => {
							that.addWatermark(res.tempFilePaths[0], type, people);
						}, 2000); // 例如等待 2 秒
					},
					fail(err) {
						console.error('拍照失败', err);
					}
				});
			},
			// 添加水印
			addWatermark(imagePath, type, people) {
				let watermarkedImagePath = null
				const that = this;
				const ctx = uni.createCanvasContext('watermarkCanvas');
				uni.getImageInfo({
					src: imagePath,
					success(res) {
						const {
							width,
							height,
							path
						} = res;
						that.canvasWidth = width
						that.canvasHeight = height
						// 绘制图片
						ctx.drawImage(imagePath, 0, 0, width, height);
						// 在图片上绘制水印
						const watermarkText = '定制客运报销专用';
						const centerX = width / 2;
						const centerY = height / 2;
						ctx.save(); // 保存当前绘图状态
						ctx.translate(centerX, centerY); // 将坐标系原点移动到画布中心
						ctx.rotate(30 * Math.PI / 180); // 旋转画布
						ctx.setFillStyle('#fffefa');
						ctx.setFontSize(60);
						ctx.setGlobalAlpha(0.7);

						const textWidth = ctx.measureText(watermarkText).width;

						// 计算文本位置
						const x = -textWidth / 2;
						const y = 60 / 2;

						// 绘制文本
						ctx.fillText(watermarkText, x, y);
						ctx.setGlobalAlpha(1);
						ctx.restore(); // 恢复到之前的绘图状态
						// 循环绘制 5 行 6 列 的文字
						/* for (let i = 1; i <= 2; i++) {
							for (let j = 1; j <= 2; j++) {
								
								// 每个水印间隔 20
								x += rowSize + 200
							}
							y += colSize
							x = -rowSize
						} */
						ctx.save();
						// 完成绘制
						ctx.draw(false, () => {
							// 导出带有水印的新图片
							setTimeout(() => {
								uni.canvasToTempFilePath({
									destWidth: width * 3,
									destHeight: height * 3,
									canvasId: 'watermarkCanvas',
									quality: 0.5,
									fileType: 'jpg',
									success(res) {
										watermarkedImagePath = res.tempFilePath
										uni.saveFile({
											tempFilePath: watermarkedImagePath,
											success(res) {
												const savedFilePath = res.savedFilePath;
												const uploadTask = uni.uploadFile({
													// url: 'https://bd.xmjdt.net:8007/api/AirTrain/Image_Tool',
													url: 'https://chuxing.mbxing.com/api/AirTrain/Image_Tool',
													filePath: savedFilePath,
													name: 'file', // 后端接收文件的字段名
													header: {
														"Content-Type": "multipart/form-data"
													},
													formData: {
														type: type,
														ticketID: people.ticketID
													},
													success: (uploadFileRes) => {
														let data = JSON.parse(uploadFileRes.data)
														if (type =='1' && data.IsSuccess) {
															people.idCardPath = data.Data
															that.showToast(`上传成功，等待工作人员审核！`,'success')
														} else if (type =='2' && data.IsSuccess) {
															people.boardingPassPath = data.Data
															that.showToast(`上传成功，等待工作人员审核！`,'success')
														} else if (type =='3' && data.IsSuccess) {
															people.ticketPath =data.Data
															that.showToast(`上传成功，等待工作人员审核！`,'success')
														} else {
															that.showToast(`上传失败，${data.Message}`,'warning')
														}
														console.log('success',uploadFileRes);
													},
													fail: (err) => {
														that.showToast(
															`上传失败!请重新选择图片。${err.errMsg}`,
															'warning'
														)
														console.error('error',err);
													},

												});
												uploadTask.onProgressUpdate((
													res) => {
													// console.log('上传进度' +
													// 	res.progress);
													// console.log(
													// 	'已经上传的数据长度' +
													// 	res
													// 	.totalBytesSent
													// );
													// console.log(
													// 	'预期需要上传的数据总长度' +
													// 	res
													// 	.totalBytesExpectedToSend
													// );
												});
											},
											fail(err) {
												console.error('保存文件失败', err);
											}

										})

										uni.hideLoading()
									},
									fail(err) {
										console.error('生成水印图片失败', err);
									}
								});
							}, 2000)
						});
					},
					fail(err) { 
						console.error('获取图片信息失败', err);
					}
				});
			},
			//--------------------时间格式化------------------------------
			timeFormat: function(time) {
				if (time) {
					var dateTime = time.replace('T', ' ');
					return dateTime.substring(0, 16);
				}
			},
			//判断状态展示颜色
			stateColor(state) {
				switch (state) {
					case 1:
					case 2: {
						return "#ff9900"
					}
					case 3:
					case 5: {
						return "#19be6b"
					}
					case 7: {
						return "#b6b6b7"
					}
					case 4:
					case 6: {
						return "#ff4939"
					}
					default:
						""
				}
			},
			//格式化时间
			formata(time) {
				if (time) {
					return `${time.substr(0,10)}
					${time.substr(11,5)}`
				}
			},
			//---------------------------------------------快捷弹窗---------------------------------------------
			showToast: function(title, type) {
				this.$refs.uToast.show({
					title: title,
					type: type
				})
			},
		}
	};
</script>

<style lang="scss" scoped>
	.page {
		padding: 20rpx;
		height: 100vh;
		width: 100%;
	}

	.title {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		margin-bottom: 20rpx;
		font-weight: 700;
	}

	.state {
		font-size: 25rpx;
		font-weight: 600;
		padding: 10rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		text-align: center;
		width: 22%;
	}

	.people {
		display: flex;
		border-radius: 10rpx;
		padding: 10rpx;
		border: solid 1rpx #aaaaaa;
		box-shadow: 5rpx 5rpx 5rpx -5rpx #aaaaaa;
		margin-bottom: 20rpx;

		.name {
			display: flex;
			justify-content: center;
			align-items: center;
			width: 22%;
		}
	}

	.photo {
		height: 200rpx;
		width: 200rpx;
		text-align: center;
		line-height: 200rpx;
		background-color: #d0d0d0;
		margin-left: 20rpx;
	}

	.mark-canvas {
		position: absolute;
		/* 将画布移出展示区域 */
		top: -700vh;
		left: -700vw;
	}

	.item {
		display: flex;
		position: relative;
		margin-bottom: 20rpx;

		.yuan {
			width: 24rpx;
			height: 24rpx;
			background-color: #4C8CFF;
			border-radius: 50%;
			position: absolute;
			top: 62rpx;
			/* margin-top: 40rpx; */
		}

		.line {
			width: 2rpx;
			height: 100%;
			background: #4C8CFF;
			margin-left: 12rpx;
			opacity: 0.3;
			position: absolute;
			top: 86rpx;
		}

		.item_txt {
			display: flex;
			width: 80%;
			height: auto;

			background: #FFFFFF;
			box-shadow: 0px 10rpx 15rpx 0px rgba(215, 215, 215, 0.4);
			border-radius: 16rpx;
			margin-left: 60rpx;
			padding: 10rpx 10rpx 0 20rpx;

			.txt {
				display: flex;
				justify-content: space-between;
				height: auto;

				width: 100%;
				margin-left: 20rpx;
				padding: 10rpx;

				.time {
					font-size: 18px;
					font-weight: 600;
					height: 40rpx;
					font-family: Adobe Heiti Std R;
					margin: 10rpx 0rpx 7rpx 0rpx;
				}

				.message {
					font-size: 15px;
					font-weight: 600;
					height: 40rpx;
					font-family: Adobe Heiti Std R;
					margin: 10rpx 0rpx 7rpx 0rpx;
				}
			}
		}
	}

	.item:last-child .line {
		display: none;
		/* 最后一个步骤不需要线条 */
	}

	.img {
		width: 200rpx;
		/* 图片宽度占据容器的100% */
		height: 200rpx;
		/* 图片高度占据容器的100% */
		object-fit: contain;
		/* 图片按比例缩小并完整显示 */
		margin-left: 20rpx;
	}
</style>